package com.xiaoming.filter;

import java.util.*;

public class Calculator {

    private static Map<String, List<Meterics>> methodMap;

    private static Map<String, List<Long>> methodTimeMap;

    public Calculator() {
        this.methodMap = new HashMap<>();
        this.methodTimeMap = new HashMap<String, List<Long>>();
    }

    public void calculate(long calculateTime) {
        long endTime = calculateTime - 5 * 1000;
        Iterator<Map.Entry<String, List<Meterics>>> iterator = methodMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, List<Meterics>> next = iterator.next();
            Iterator<Meterics> metericsIterator = next.getValue().iterator();
            List<Long> metericsList = new ArrayList<>();
            while (metericsIterator.hasNext()) {
                Meterics meterics = metericsIterator.next();
                if (meterics.getStarTime() <= endTime) {
                    metericsList.add(meterics.getDuration());
                }
            }
            methodTimeMap.put(next.getKey(), metericsList);
        }
    }

    public void outPutTop() {
        Iterator<Map.Entry<String, List<Long>>> iterator = methodTimeMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, List<Long>> item = iterator.next();
            long count = item.getValue().stream().count();
            double top90 = Math.ceil((double) count * 90 / 100);
            double top99 = Math.ceil((double) count * 90 / 100);
            System.out.println(String.format(" %s 的 top90 是：%s ， top99 是：%s", item.getKey(), top90, top99));
        }
    }

    public void put(String methodName, Meterics meterics) {
        List<Meterics> times = methodMap.get(methodName);
        if (times != null) {
            times.add(meterics);
        } else {
            List<Meterics> metericsList = new LinkedList<>();
            metericsList.add(meterics);
            methodMap.put(methodName, metericsList);
        }
    }
}
